<?php
namespace Api\Controller;
use Common\Controller\ApiController;

class GListController extends ApiController {
    
    function _initialize() {
        parent::_initialize();
        //验证 APP KEY
        $timestamp = I('request.timestamp');
        $token = I('request.token');
        parent::checkAppToken($token,$timestamp);
    }

    //商品分类
    public function category() {
        $data['code'] = '200';
        $data['msg'] = '';
        $ModelGoodsCat =  new \Home\Model\GoodsCatModel();
        $category = $ModelGoodsCat->show_list();
        foreach($category as $k => $v) {
            if(empty($category[$k]['sub'])) {
                if(!empty($v['ico'])) {
                        $v['ico'] = get_host().__ROOT__.$v['ico'];
                }
                $category[$k]['sub'][0] = $v;
            } else {
                foreach($category[$k]['sub'] as $k2 => $v2) {
                    if(!empty($v2['ico'])) {
                        $category[$k]['sub'][$k2]['ico'] = get_host().__ROOT__.$v2['ico'];
                    }
                }
            }
        }
        $data['data'] = $category;
        $this->response($data,C('API_TYPE'));
    }
    
    //获得首页热门商品
    public function get_hot_goods($limit) {
        $data['code'] = '200';
        $data['msg'] = '';
        $ModelGoods = new \Home\Model\GoodsModel();
        
        $map['is_index'] = 1;
        $map['status'] = 1;
        $result = $ModelGoods->search($map,$limit);
        $goods_list = $result['list'];
        foreach($goods_list as $k => $v) {
            $goods_list[$k]['picture'] = get_host().__ROOT__.str_replace("goods/", 'goods/thumb/',$v['picture']);
            if(empty($v['count_sale'])){
                $goods_list[$k]['count_sale'] = 0;
            }
            if(empty($v['price'])){
                $goods_list[$k]['price'] = "0";
            }
        }
        $data['page_count'] = $result['page_count'];
        $data['data'] = $goods_list;
        $this->response($data,C('API_TYPE'));
    }
    
    //获取品牌筛选
    public function get_filter_brand($cid,$price,$keywords) {
        $ModelGoods = new \Home\Model\GoodsModel();
        $map['cid'] = $cid;
        $map['keywords'] = $keywords;
        $map['price'] = $price;
        $brand_list = $ModelGoods->get_search_brand($map);
        
        $data['code'] = '200';
        $data['msg'] = '';
        $data['data'] = $brand_list;
        
        $this->response($data,C('API_TYPE'));
    }
    
    //获得子类别筛选
    public function get_sub_cat($cid,$bid=0,$keywords) {
        $ModelGoodsCat =  new \Home\Model\GoodsCatModel();
        $cat_list = $ModelGoodsCat->get_search_sub($cid,$keywords,$bid);
        
        $data['code'] = '200';
        $data['msg'] = '';
        $data['data'] = $cat_list;
        
        $this->response($data,C('API_TYPE'));
    }  
    
    public function goods_list() {
        //初始化模型
        $ModelGoodsCat =  new \Home\Model\GoodsCatModel();
        $ModelGoods = new \Home\Model\GoodsModel();
        $ModelGoodsBrand = new \Home\Model\GoodsBrandModel();
        $M_attr = D('goods_mod_attr');
        $M_mod_sel = D('goods_mod_sel');
        
        //获取参数
        $cid = I('get.cid',0); //已选类别
        $bid = I('get.bid',0); //已选品牌
        $price = I('get.price',''); //价格
        $this->price = $price;
        $o = I('get.o','');
        $keywords = I('get.keywords','');
        $pagesize = I('get.pagesize',10);
        $this->keywords = $keywords;
        $this->order = $o;
        $this->cid = $cid;
        
        //搜索参数URL路径
        $url_arr = array(); //URL路径数组
        $url_arr['cid'] = $cid;
        //获取自定义参数
        foreach($_GET as $k => $v) {
            if(strpos($k,'attr_') === 0) {
                $url_arr[$k] = $v;
            }
        }
        $url_arr['price'] = $price;
        $url_arr['bid'] = $bid;
        $url_arr['o'] = $o;
        $url_arr['keywords'] = $keywords;
        
        //筛选类别
        $cat_list = $ModelGoodsCat->get_search_sub($cid,$keywords,$bid);//类别筛选
        //赋值类别URL
        foreach($cat_list as $k => $v) {
            $cat_list[$k]['url'] = U('GList/index',array('cid'=>$v['cat_id'],'keywords'=>$keywords,'bid'=>$bid));
        }
        
        //筛选自定义属性
        $attr_list = $ModelGoods->get_search_arr($url_arr); 
       
        //商品
        $result2 = $ModelGoods->search($url_arr,$pagesize);//获得查询结果
        $goods_list = $result2['list'];//当前页数据
        foreach($goods_list as $k => $v) {
            $goods_list[$k]['picture'] = get_host().__ROOT__.str_replace("goods/", 'goods/thumb/',$v['picture']);
            if(empty($v['count_sale'])){
                $goods_list[$k]['count_sale'] = 0;
            }
        }
       
        $result['list'] = $goods_list;
        $result['total'] = $result2['count'];//总记录数
        $result['page_count'] = $result2['page_count'];
        $result['current_page'] = I('get.p',1);//当前第几页
        $result['attr_list'] = $attr_list;
        $result['cat_list'] = $cat_list;
        
        $data['code'] = '200';
        $data['msg'] = '';
        $data['data'] =$result;
        $this->response($data,C('API_TYPE'));
    }
    
    /**
     * 商品详情页
     * @param int $id 商品ID
     */
    public function goods_info($id,$item_id = 0) {
        $ModelGoods = new \Home\Model\GoodsModel();
        $ModelGoodsCat = new \Home\Model\GoodsCatModel();
        $goods = $ModelGoods->find($id); //获得商品详细信息
        
        //类别名称
        $goods['cat_name'] = $ModelGoodsCat->getAllPathName($goods['cat_ids']);
        //大图展示
        $goods['picture_list'] = str_replace(",,", ",", $goods['picture_list']);
        if(!empty($goods['picture_list'])) {
            $goods['arr_picture_list'] = explode(',', trim($goods['picture_list'],','));
            if(!empty($goods['arr_picture_list'])){
                foreach($goods['arr_picture_list'] as $k => $v) {
                    if($v !== '') {
                        $goods['arr_picture_list'][$k] = get_host().__ROOT__.$v;
                    }
                }
            }
        } else {
            $goods['arr_picture_list'] = null;
        }
        $goods['arr_picture_1'] = $goods['arr_picture_list'][0];
        
        $goods['price_cha'] = $goods['price_market'] - $goods['price'];
        //品牌
        $BrandObj = new \Home\Model\GoodsBrandModel();
        $goods['brand_name'] = $BrandObj->get_name($goods['brand_id']);
        
        //筛选参数解析JSON
        $goods['spec_array'] = stripslashes($goods['spec_array']);
        $arr_par = json_decode($goods['spec_array'],true);
        
        //默认单件
        $item1 = $ModelGoods->get_item_first($id,$item_id);
        $goods['item_list'] = $ModelGoods->get_item($id);
       
        //如果筛选参数不为空
        if(!empty($arr_par)) {
            foreach($arr_par as $k2 => $v2) {
                $arr_par[$k2]['sub'] = explode('|', $v2['val']);
                //过滤不存在选项
                foreach($arr_par[$k2]['sub'] as $k3 => $v3) {
                    $par = $v2['name'].':'.$v3;
                    if($ModelGoods->exist_item($id, $par) <= 0) {
                        unset($arr_par[$k2]['sub'][$k3]);
                    }
                }
                $arr_par_name[$v2['id']] = $v2['name'];
            }
            $goods['arr_par'] = $arr_par;
            $goods['arr_par_name'] = $arr_par_name;
           //默认选择单件
            $arr_sel = array(); //默认单件选择数组
            $spec_array = $item1['spec_array'];
            $arr_spec_array = explode(',', $spec_array);
            foreach($arr_spec_array as $v) {
                $arr2 = explode(':', $v);
                //获得attr_id
                foreach($arr_par as $par) {
                    if($par['name'] == $arr2[0]) {
                       $arr_2_id = $par['id']; 
                    }
                }
                $arr_sel[$arr_2_id] = $arr2[1];
            }
            $goods['arr_sel'] = $arr_sel;
            
        }
        $goods['item_id'] = $item1['item_id'];
        
        
        //评价数量及星级
        $GoodsCommentObj = new \Home\Model\GoodsCommentModel();
        $goods['count_comment'] = $GoodsCommentObj->count_goods($id);//商品评价数
        $goods['comment_star'] = $GoodsCommentObj->comment_star($id);//商品星级
        $goods['count_star_12'] = $GoodsCommentObj->count_star_12($id);//差评数
        $goods['count_star_3'] = $GoodsCommentObj->count_star_3($id);//中评数
        $goods['count_star_45'] = $GoodsCommentObj->count_star_45($id);//好评数
        $goods['percent_star_3'] = floor($this->count_star_3/$this->count_comment*100);
        $goods['percent_star_12'] = floor($this->count_star_12/$this->count_comment*100);
        $goods['percent_star_45'] = 100-$this->percent_star_3-$this->percent_star_12;
        
        //商品自定义参数
        $par_arr = $ModelGoods->get_goods_attr($goods['model_id'], $id);
        $goods['par_arr'] = $par_arr;
        
        $goods['detail'] = htmlspecialchars_decode($goods['detail']);
        $goods['detail'] = str_replace('/fangwei_shop3/Public/upload/', get_host().'/fangwei_shop3/Public/upload/', $goods['detail']);
        
        //增加商品点击量
        $ModelGoods->add_hits($id);
        
        $data['code'] = '200';
        $data['msg'] = '';
        $data['data'] =$goods;
        $this->response($data,C('API_TYPE'));
    }
    
    /**
     * 显示商品详细介绍
     * @param int $id
     */
     public function show_detail($id) {
        $ModelGoods = new \Home\Model\GoodsModel();
        $data = $ModelGoods->field('detail')->find($id);
        $this->detail = $data['detail'];
        $this->display('show_detail');
    }
    
     /**
     * 显示商品评论
     * @param int $id
     */
     public function show_comment($id) {
   
        //评价数量及星级
        $GoodsCommentObj = new \Home\Model\GoodsCommentModel();
        $this->count_comment = $GoodsCommentObj->count_goods($id);//商品评价数
        $this->comment_star = $GoodsCommentObj->comment_star($id);//商品星级
        $this->count_star_12 = $GoodsCommentObj->count_star_12($id);//差评数
        $this->count_star_3 = $GoodsCommentObj->count_star_3($id);//中评数
        $this->count_star_45 = $GoodsCommentObj->count_star_45($id);//好评数
        $this->percent_star_3 = floor($this->count_star_3/$this->count_comment*100);
        $this->percent_star_12 = floor($this->count_star_12/$this->count_comment*100);
        $this->percent_star_45 = 100-$this->percent_star_3-$this->percent_star_12;
        
        //商品评价
        $comment = $GoodsCommentObj->search($id);
        $comment_list = $comment['list'];
        $comment_page = $comment['page'];
        $total_page = $comment['total_page'];
        $MemberObj = new \Home\Model\MemberModel();
        foreach($comment_list as $k => $v) {
            $comment_list[$k]['headpic'] = $MemberObj->get_headpic($v['member_id']);
            $comment_list[$k]['member_name'] = $MemberObj->show_member_name($v['member_id']);
        }
        $this->comment_list = $comment_list;
        $comment_page = preg_replace('/p=(\d+)/', "p=$1#3", $comment_page);
        $this->comment_page = $comment_page;
        
        
        $this->display('show_comment');
    }
    
    /**
     * 获得单件JSON数据
     * @param int $goods_id 商品ID
     * @param string $spec 规格参数
     */
    public function info_item($goods_id,$spec) {
        $ModelGoods = new \Home\Model\GoodsModel();
        $row = $ModelGoods->get_item_spec($goods_id, $spec);
        if(!empty($row)) {
            $data['code'] = '200';
            $data['msg'] = '';
            $data['data'] = $row;
        } else {
            $data['code'] = '500';
            $data['msg'] = '不存在单件';
            $data['data'] = null;
        }
        $this->response($data,C('API_TYPE'));
    }
    
     /**
     * 商品收藏
     * @param int $goods_id 商品ID
     */
    public function add_fav($member_id,$goods_id,$item_id) {
        $data['code'] = '200';
        $data['msg'] = '';
        if (empty($member_id)) {
            $data['code'] = '500';
            $data['msg'] = '请先登录或注册！';
        } else {
            $GoodsItemObj = M('goods_item');
            $price = $GoodsItemObj->where(array('goods_id'=>$goods_id,'item_id'=>$item_id))->getField('price');
            $FavObj = new \Home\Model\MemberFavModel();
            $flag = $FavObj->add_fav_app($member_id, $goods_id,$item_id, $price);
            if($flag > 0) {
                $data['msg'] = '收藏成功！';
                $data['data'] = "1";
            } elseif ($flag == -2) {
                $data['msg'] = '取消收藏成功';
                $data['data'] = "2";
            } else {
                $data['code'] = '500';
                $data['msg'] = '收藏失败！';
            }
        }
        $this->response($data,C('API_TYPE'));
    }
    
    /**
     * 是否已收藏
     * @param int $goods_id 商品ID
     */
    public function is_fav($member_id,$goods_id,$item_id) {
        $data['code'] = '200';
        $data['msg'] = '';
        $MemberFavModel = new \Home\Model\MemberFavModel();
        $count = $MemberFavModel->where(array('member_id'=>$member_id,'goods_id'=>$goods_id,'item_id'=>$item_id))->count();
        if($count > 0) {
            $data['data'] = 1;
        } else {
            $data['data'] = 0;
        }
        $this->response($data,C('API_TYPE'));
    }
    
}